import { useRouter } from "vue-router";
import { useStore } from "vuex";
import ACCESS_EUNM from "@/access/ACCESS_EUNM";
import router from "@/router";
import store from "@/store";
import verifyAccess from "@/access/VerifyAccess";

router.beforeEach(async (to, from, next) => {
  const needAccess = to?.meta?.access ?? ACCESS_EUNM.LOGIN_FAILURE;
  let loginUser = store.state.user.loginUser;
  if (!loginUser || !loginUser.userRole) {
    await store.dispatch("user/getLoginUser");
    loginUser = store.state.user.loginUser;
  }
  if (needAccess !== ACCESS_EUNM.LOGIN_FAILURE) {
    if (
      !loginUser.userRole ||
      loginUser.userRole === ACCESS_EUNM.LOGIN_FAILURE
    ) {
      next(`user/login?redirect=${to.path}`);
      return;
    }
    if (!verifyAccess(loginUser, needAccess as string)) {
      next("/noAuth");
      return;
    }
  }
  next();
});
